package cn.hinglo.gameclaw.im.service;

import cn.hinglo.gameclaw.im.bean.LiveRoom;
import cn.hinglo.gameclaw.im.dao.LiveRoomDao;
import cn.hinglo.gameclaw.im.utils.HttpClientUtils;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @createTime: 2018/5/3
 * @author: HingLo
 * @description: 直播地址管理
 */
@Service
@CacheConfig(cacheNames = "live")
public class LiveRoomService {

    private static final String URL = "https://vcloud.163.com/app/channel/";
    private final LiveRoomDao liveRoomDao;

    @Autowired
    public LiveRoomService(LiveRoomDao liveRoomDao) {
        this.liveRoomDao = liveRoomDao;
    }

    /**
     * 从本地数据库中查询直播地址列表
     *
     * @return 直播地址集合
     */
    public List<LiveRoom> listService() {
        return liveRoomDao.selectAll();
    }

    /**
     * 通过直播地址的唯一Id来查询
     *
     * @param id 直播地址的唯一Id
     * @return 直播间信息
     */
    @Cacheable(key = "#id")
    public LiveRoom queryByIdLiveRoomService(String id) {
        return liveRoomDao.selectByPrimaryKey(id);
    }

    /**
     * 创建直播频道,如果创建成功就将直播频道的信息保存到数据中<br>
     * 需要开启事务
     *
     * @param name 频道名称
     * @param type 频道类型
     * @return 是否创建成功
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean createService(String name, Integer type) {

        Map<String, Object> param = new HashMap<>(2);
        param.put("name", name);
        param.put("type", type);
        String result = HttpClientUtils.postFormData(URL + "create", param, true);
        if (HttpClientUtils.getCode(result)) {
            Object res = HttpClientUtils.getResult(result, "ret");
            LiveRoom liveRoom = JSONUtil.toBean(JSONUtil.parseObj(res), LiveRoom.class);
            if (liveRoomDao.insert(liveRoom) > 0) {
                return true;
            } else {
                //如果数据库创建失败了，就直接删除远程的直播间
                //获取直播间的唯一id
                String cid = HttpClientUtils.getResult(result, "ret.id");
                param.clear();
                param.put("cid", cid);
                //请求删除，不做判断是否删除成功
                HttpClientUtils.postFormData(URL + "create", param, true);
                return false;
            }

        } else {
            return false;
        }
    }

    /**
     * 创建直播频道,如果创建成功就将直播频道的信息保存到数据中<br>
     * 需要开启事务
     *
     * @param name 频道名称
     * @param type 频道类型
     * @return 是否创建成功
     */
    public LiveRoom createBeanService(String name, Integer type) {

        Map<String, Object> param = new HashMap<>(2);
        param.put("name", name);
        param.put("type", type);
        String result = HttpClientUtils.postFormData(URL + "create", param, true);
        if (HttpClientUtils.getCode(result)) {
            Object res = HttpClientUtils.getResult(result, "ret");
            return JSONUtil.toBean(JSONUtil.parseObj(res), LiveRoom.class);

        }
        return null;
    }


    /**
     * 删除指定的直播频道是数据库与网易云中同时删除
     *
     * @param cid 直播间的唯一Id
     * @return 是否删除成功
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean deleteService(String cid) {
        LiveRoom liveRoom = new LiveRoom();
        liveRoom.setCid(cid);
        if (liveRoomDao.delete(liveRoom) == 1) {
            Map<String, Object> param = new HashMap<>(1);
            param.put("cid", cid);
            String result = HttpClientUtils.postFormData(URL + "create", param, false);
            if (HttpClientUtils.getCode(result)) {
                return true;
            } else {
                throw new RuntimeException("删除失败");
            }
        } else {
            return false;
        }

    }

    /**
     * 保存直播频道
     *
     * @param liveRoom1 前摄像头
     * @param liveRoom2 后摄像头
     * @return 是否保存成功
     */
    @CacheEvict(allEntries = true, condition = "#result==true")
    public boolean saveService(LiveRoom liveRoom1, LiveRoom liveRoom2) {
        return liveRoomDao.insert(liveRoom1) == 1 && liveRoomDao.insert(liveRoom2) == 1;
    }
}
